<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>CPA数据管理</el-breadcrumb-item>
      <el-breadcrumb-item>客户&渠道管理</el-breadcrumb-item>
      <el-breadcrumb-item>
        <span
          class="u-cursor"
          @click="$router.replace('/cpa/customer-pro')"
        >产品管理</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>新建产品</el-breadcrumb-item>
    </el-breadcrumb>

    <Container class="u-pb60">
      <el-form
        ref="form"
        :model="pro_from"
        label-width="160px"
        class="m-form--detail"
      >
        <el-form-item label="客户名称：">
          <el-select
            size="small"
            style="width: 400px;"
            v-model="pro_from.customerCode"
            filterable
            placeholder="请选择"
            @change="cusSelect"
            :disabled="dateStatus"
          >
            <el-option
              v-for="item in customer_items.options "
              :key="item.customerCode"
              :label="item.name"
              :value="item.customerCode"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称：">
          <el-select
            size="small"
            style="width: 400px;"
            v-model="pro_from.productName"
            placeholder="请选择"
            :disabled="dateStatus"
            filterable
          >
            <el-option
              v-for="(item, index) in pro_items.options"
              :key="index"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务类型：">
          <el-select
            size="small"
            style="width: 400px;"
            v-model="pro_from.cooperativeMode"
            :placeholder="cooperativeMode_items.placeHolder"
            filterable
          >
            <el-option
              v-for="item in cooperativeMode_items.options"
              :key="item.id"
              :label="item.value"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上游渠道号：">
          <el-input
            size="small"
            style="width: 400px;"
            v-model="pro_from.productChannelCode"
            placeholder="请输入上游渠道号"
          ></el-input>
        </el-form-item>
        <el-form-item label="康远渠道号：">
          <el-input
            size="small"
            style="width: 400px;"
            v-model.trim="pro_from.kyProductChannelCode"
            placeholder="请输入康远渠道号"
          ></el-input>
        </el-form-item>
        <el-form-item label="填充渠道包：">
          <el-radio-group
            size="small"
            v-model="channelPackstatus"
          >
            <el-radio :label="1">填充渠道链接</el-radio>
            <el-radio :label="0">上传渠道包</el-radio>
          </el-radio-group>
          <br>
          <el-input
            size="small"
            style="width: 400px;"
            v-model="pro_from.packageLink"
            placeholder="请输入渠道链接"
            v-if="channelPackstatus=='1'"
            class="blockBox"
          ></el-input>
          <el-upload
            :action="apiUrl.uploadApk"
            :with-credentials="true"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :beforeUpload="beforeAvatarUpload"
            :onError="uploadError"
            :file-list="fileList"
            v-if="channelPackstatus=='0'"
          >
            <el-button
              size="small"
              type="primary"
            >点击上传</el-button>
            <div slot="tip">只能上传apk文件，且不超过2MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="选择后台账号：">
          <el-select
            size="small"
            style="width: 400px;"
            v-model="pro_from.backendAccountId"
            placeholder="请选择"
            filterable
          >
            <el-option
              v-for="item in adminSysAccounts"
              :key="item.id"
              :label="item.account"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="接入价："
          style="margin-bottom: 0;"
        >
          <el-form-item
            style="margin-bottom: 15px;"
            v-for="(item,index) in pro_from.prices"
            :key="item.id"
            v-show="!item.deleted"
          >
            <el-date-picker
              size="small"
              style="width: 195px;"
              v-model="item.date"
              type="date"
              placeholder="选择日期"
              @change="dateChange(index)"
            >
            </el-date-picker>
            <el-input
              size="small"
              style="width: 195px; margin-left: 10px;"
              v-model="item.price"
              placeholder="请输入接入价(元)"
              @change="priceInputChange(index)"
            ></el-input>
            <el-button
              size="small"
              style="margin-left: 10px;"
              v-if="index === 0"
              @click="addRow"
            >添加</el-button>
            <el-button
              size="small"
              style="margin-left: 10px;"
              v-if="index !== 0"
              @click="deletePrice(index)"
            >删除</el-button>
            <span
              style="margin-left:10px;color:red;"
              v-if="item.disexist"
            >* 已存在</span>
          </el-form-item>
        </el-form-item>
      </el-form>
    </Container>
    <Affix :offset-bottom="0">
      <ButtonGroup
        isFixed
        align="right"
      >
        <el-button
          size="small"
          @click="go_back()"
        >返回</el-button>
        <el-button
          size="small"
          type="primary"
          @click="onSubmit"
        >确认</el-button>
      </ButtonGroup>
    </Affix>
  </div>
</template>

<script>
import Container from "@/components/container";
import Affix from "@/components/affix";
import ButtonGroup from "@/components/button-group";

export default {
  components: {
    Container,
    Affix,
    ButtonGroup
  },
  data() {
    return {
      pageTitle: "创建产品信息",
      menu_nav: ["CPA数据管理", "客户产品管理", "创建产品信息"],
      isRightBox: false,
      dateStatus: false,
      uploadButStatus: true,
      fileList: [],
      pro_from: {
        backendAccountId: "",
        cooperativeMode: "",
        customerCode: "",
        kyProductChannelCode: "",
        packageLink: "",
        prices: [
          {
            date: "",
            id: "",
            disable: false,
            disexist: false,
            price: ""
          }
        ],
        productChannelCode: "",
        productCode: "",
        productName: ""
      },
      channelPackstatus: 1,
      proStatus: 0,
      customer_items: {
        placeHolder: "客户",
        options: []
      },
      pro_items: {
        placeHolder: "产品",
        options: []
      },
      cooperativeMode_items: {
        model_value: "",
        placeHolder: "业务类型",
        options: []
      },
      adminSysAccounts: [],
      customerId: "",
      customerCode: ""
    };
  },
  created() {
    this.customerId = this.$route.query.customerId;
    this.proInfo();
    if (this.customerId != "") {
      this.pageInfo().then(() => {
        this.customerSelect();
        this.businessModel();
      });
      this.pageTitle = "编辑产品信息";
      //                this.isRightBox = this.dateStatus = true;
      this.dateStatus = true;
    } else {
      this.customerSelect();
      this.businessModel();
    }
  },
  methods: {
    customerSelect() {
      /*客户*/
      this.$http({
        method: "get",
        url: this.apiUrl.customerSearch,
        params: {
          offset: 1,
          limit: 9999,
          val: ""
        }
      })
        .then(res => {
          if (res.status == 200) {
            var data = res.data;
            this.customer_items.options = data.items;
          }
        })
        .catch(() => {});
    },
    proInfo() {
      /*产品*/
      this.$http({
        method: "get",
        url: "/cpa/api/customer_product_name/all_product_name"
      })
        .then(res => {
          if (res.status == 200) {
            this.pro_items.options = res.data.list;
            this.pro_from.productName = "";
          }
        })
        .catch(() => {});
    },
    adminSysInfo() {
      var id;
      if (this.pro_from.customerID) {
        id = this.pro_from.customerID;
      } else {
        this.customer_items.options.forEach(item => {
          if (item.customerCode == this.pro_from.customerCode) {
            id = item.id;
          }
        });
      }
      /*新建产品的客户后台账号列表*/
      this.$http({
        method: "get",
        url: this.apiUrl.customerGet,
        params: {
          id: id
        }
      })
        .then(res => {
          if (res.status == 200) {
            var data = res.data;
            this.adminSysAccounts = data.adminSysAccounts;
            this.adminSysAccounts.map((item, index) => {
              if (item.account == "") {
                this.adminSysAccounts.splice(index, 1);
              }
            });
          }
        })
        .catch(() => {});
    },
    businessModel() {
      /*业务类型*/
      this.$http({
        method: "get",
        url: this.apiUrl.customerProListBiztype
      })
        .then(res => {
          if (res.status == 200) {
            var data = res.data;
            this.cooperativeMode_items.options = data.lists;
          }
        })
        .catch(() => {});
    },
    pageInfo() {
      return this.$http({
        method: "get",
        url: this.apiUrl.customerProGet,
        params: {
          id: this.customerId
        }
      })
        .then(res => {
          if (res.status === 200) {
            this.pro_from = res.data;
            this.pro_from.cooperativeMode == 0
              ? (this.pro_from.cooperativeMode = "")
              : null;
          }
        })
        .catch(() => {});
    },
    cusSelect() {
      this.proInfo();
      this.adminSysInfo();
      if (this.customerId == "") {
        this.pro_from.productCode = this.pro_from.backendAccountId = "";
      }
    },
    onSubmit() {
      delete this.pro_from.adminSysAccounts;
      //                this.pro_from.cooperativeMode=parseInt(this.pro_from.cooperativeMode);
      if (this.customerId == "" && this.proStatus == 0) {
        delete this.pro_from.productCode;
      } else if (this.customerId == "" && this.proStatus == 1) {
        delete this.pro_from.productName;
      }
      var pricesArr = this.pro_from.prices;
      var pricesLen = pricesArr.length;
      let isexist = false; //判断是否有重复的接入价
      if (this.customerId != "" && this.customerId) {
        for (let i = 0; i < pricesLen; i++) {
          if (
            (pricesArr[i].date == "" ||
              pricesArr[i].price == "" ||
              !pricesArr[i].date) &&
            !pricesArr[i].deleted
          ) {
            this.$message({
              type: "info",
              message: "接入价不能为空，请修改并重新提交"
            });
            return false;
          }
          if (pricesArr[i].disexist) {
            isexist = true;
          }
        }
      } else {
        for (let i = 0; i < pricesLen; i++) {
          if (
            pricesArr[i].date == "" ||
            pricesArr[i].price == "" ||
            !pricesArr[i].date
          ) {
            pricesArr.splice(i, 1);
            i--;
            pricesLen = pricesArr.length;
          } else if (pricesArr[i].disexist) {
            isexist = true;
          }
        }
      }
      if (isexist) {
        this.$message({
          type: "info",
          message: "存在重复的接入价，请修改或删除并重新提交"
        });
        return false;
      }
      if (pricesLen == 0) {
        this.addRow();
      }
      var url = this.apiUrl.customerProNew;
      this.customerId != "" ? (url = this.apiUrl.customerProUpdate) : null;
      this.$http({
        method: "post",
        url: url,
        data: this.pro_from
      })
        .then(res => {
          if (res.status == 200) {
            var data = res.data;
            if (data.id >= 0) {
              if (data.status == 2) {
                this.$message({
                  type: "info",
                  message: data.msg
                });
              } else {
                this.$message({
                  type: "success",
                  message: "操作成功"
                });
                this.go_back();
              }
            } else {
              this.$message({
                type: "error",
                message: "操作失败"
              });
            }
          } else {
            this.$message({
              type: "error",
              message: "操作失败，请完善信息，并重新提交"
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "error",
            message: "请完善信息，并重新提交"
          });
        });
    },
    go_back() {
      this.$router.back();
    },
    handleRemove() {
      this.uploadButStatus = true;
      this.fileList = [];
      this.pro_from.packageLink = "";
    },
    handleSuccess(response, file) {
      this.fileList.push({
        name: file.name,
        url: response.url
      });
      if (response.status == 1) {
        this.pro_from.packageLink = response.url;
        this.uploadButStatus = false;
      }
    },
    // 上传错误
    uploadError() {
      this.$message({
        type: "error",
        message: "上传失败，请重试"
      });
    },
    // 上传前对文件的大小的判断
    beforeAvatarUpload(file) {
      if (!this.uploadButStatus) {
        this.$message({
          type: "info",
          message: "只能上传一个包，您可删除已选，重新上传"
        });
        return false;
      }
      if (this.fileList.length >= 1) {
        return false;
      }
      var fileName = file.name.split(".");
      var fileNameLen = fileName.length - 1;
      const extension = fileName[fileNameLen] === "apk";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!extension) {
        this.$message({
          type: "info",
          message: "上传渠道包只能是 apk 格式"
        });
      }
      if (!isLt2M) {
        this.$message({
          type: "info",
          message: "上传包大小不能超过 2MB"
        });
      }
      return extension && isLt2M;
    },
    dateChange(index) {
      var date = this.pro_from.prices[index].date || "";
      if (date != "" && date != "undefined" && typeof date != "undefined") {
        this.pro_from.prices[index].date = this.formatDateTime(
          new Date(date),
          "y-m-d"
        );
      } else {
        this.pro_from.prices[index].date = "";
      }
      this.priceInputChange(index);
    },
    addRow() {
      this.pro_from.prices.push({
        date: "",
        disable: false,
        disexist: false,
        deleted: false,
        price: ""
      });
    },
    deletePrice(index) {
      var pricesArr = this.pro_from.prices;
      var pricesLen = pricesArr.length;
      let isexist = false; //判断是否有重复的接入价
      if (this.customerId != "" && this.customerId) {
        for (let i = 0; i < pricesLen; i++) {
          if (pricesArr[i].disexist) {
            isexist = true;
          }
        }
      }
      if (isexist) {
        this.$message({
          type: "info",
          message: "存在重复的接入价，请修改后再进行删除"
        });
        return false;
      }
      this.pro_from.prices[index].deleted = true;
      this.pro_from.prices[index].disexist = false;
    },
    priceInputChange(index) {
      let priceArr = this.pro_from.prices;
      let obj = this.pro_from.prices[index];
      if (obj.price && obj.date) {
        try {
          priceArr.forEach((item, i) => {
            if (
              i != index &&
              item.date == obj.date &&
              item.price &&
              !item.deleted
            ) {
              obj.disexist = true;
              // foreach.break = new Error("StopIteration");
            } else if (
              i != index &&
              item.date != obj.date &&
              item.price &&
              !item.deleted
            ) {
              obj.disexist = false;
            }
          });
        } catch (e) {
          if (e.message === "foreach is not defined") {
            return;
          } else throw e;
        }
      } else {
        priceArr.forEach((item, i) => {
          if (item.disexist && item.date && item.price) {
            let flag = true;
            priceArr.forEach((c, x) => {
              if (i != x && item.date == c.date && c.price) {
                flag = false;
              }
            });
            flag ? (item.disexist = false) : null;
          } else {
            item.disexist = false;
          }
        });
      }
    }
  }
};
</script>
